package com.jic.veteran.portal.service.impl;

import cn.hutool.core.date.DateUtil;
import com.jic.veteran.common.api.CommonResult;
import com.jic.veteran.common.api.ResultCode;
import com.jic.veteran.mapper.UmsMemberMapper;
import com.jic.veteran.model.UmsMember;
import com.jic.veteran.model.UmsMemberExample;
import com.jic.veteran.portal.domain.MemberDetails;
import com.jic.veteran.portal.service.UmsMemberCacheService;
import com.jic.veteran.portal.service.UmsMemberService;
import com.jic.veteran.security.util.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Random;

/**
 * 会员管理Service实现类
 * Created by macro on 2018/8/3.
 */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UmsMemberServiceImpl.class);
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UmsMemberMapper memberMapper;
    @Autowired
    private UmsMemberCacheService memberCacheService;
    @Value("${redis.key.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    @Value("${redis.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;

    @Override
    public UmsMember getByUsername(String username) {
        UmsMember member = memberCacheService.getMember(username);
        if(member!=null) return member;
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            member = memberList.get(0);
            memberCacheService.setMember(member);
            return member;
        }
        return null;
    }

    @Override
    public Integer updatePhonePasswd(Long id,Long phone, String password) {

        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andPhoneEqualTo(phone.toString())
                .andIdNotEqualTo(id);
        List<UmsMember> memberList = memberMapper.selectByExample(example);

        if (memberList.size() > 0) {
            return -1;
        }

        UmsMemberExample umsMemberExample = new UmsMemberExample();
        umsMemberExample.createCriteria().andIdEqualTo(id);
        UmsMember umsMember = memberMapper.selectByPrimaryKey(id);

        umsMember.setPhone(phone.toString());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        umsMember.setPassword(encoder.encode(password));

        int result = memberMapper.updateByExampleSelective(umsMember,umsMemberExample);
        if(result >0) {
            List<UmsMember> umsMemberCaches = memberMapper.selectByExample(umsMemberExample);
            if(!umsMemberCaches.isEmpty()) {
                memberCacheService.setMember(umsMemberCaches.get(0));
            }
        }
        return result;
    }

    @Override
    public UmsMember getByPhone(Long phone) {
        UmsMember member = memberCacheService.getPhone(phone);
        if(member!=null) return member;
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andPhoneEqualTo(phone.toString());
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            member = memberList.get(0);
            memberCacheService.setMember(member);
            return member;
        }
        return null;
    }

    @Override
    public UmsMember getById(Long id) {
        return memberMapper.selectByPrimaryKey(id);
    }

    @Override
    public void create(UmsMember umsMember) {
        umsMember.setLoginTime(DateUtil.date());
        int result = memberMapper.insert(umsMember);
        if(result > 0) {
            UmsMemberExample example = new UmsMemberExample();
            example.createCriteria().andUsernameEqualTo(umsMember.getUsername());
            List<UmsMember> memberList = memberMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(memberList)) {
                UmsMember member = memberList.get(0);
                memberCacheService.setMember(member);
            }
        }
    }

    @Override
    public void update(String openid,UmsMember umsMember) {
        UmsMemberExample umsMemberExample = new UmsMemberExample();
        umsMemberExample.createCriteria().andOpenIdEqualTo(openid);
        umsMember.setOpenId(openid);
        int result = memberMapper.updateByExampleSelective(umsMember,umsMemberExample);
        if(result >0) {
            List<UmsMember> umsMemberCaches = memberMapper.selectByExample(umsMemberExample);
            if(!umsMemberCaches.isEmpty()) {
                memberCacheService.setMember(umsMemberCaches.get(0));
            }
        }
    }

    @Override
    public String generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for(int i=0;i<6;i++){
            sb.append(random.nextInt(10));
        }
        memberCacheService.setAuthCode(telephone,sb.toString());
        return sb.toString();
    }

    @Override
    public UmsMember getCurrentMember() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
        return memberDetails.getUmsMember();
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        UmsMember member = getByUsername(username);
        if(member!=null){
            return new MemberDetails(member);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    @Override
    public String getToken(String username, String password) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(username);
//            if(!passwordEncoder.matches(password,userDetails.getPassword())){
//                throw new BadCredentialsException("密码不正确");
//            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    @Override
    public String refreshToken(String token) {
        return jwtTokenUtil.refreshHeadToken(token);
    }

    //对输入的验证码进行校验
    private boolean verifyAuthCode(String authCode, String telephone){
        if(StringUtils.isEmpty(authCode)){
            return false;
        }
        String realAuthCode = memberCacheService.getAuthCode(telephone);
        return authCode.equals(realAuthCode);
    }

}
